import React, {Component} from 'react'
import T from 'prop-types'

import WeaNewScroll from '../wea-new-scroll';


class WeaNewScrollPagination extends Component {
    constructor(props) {
        super(props)
        this.timeout = null;
        this.startTime = new Date().getTime();
    }
    
    scrollTop() {
        let dom = ReactDOM.findDOMNode(this);
        let scroller = jQuery(dom).children().children(".scroller");
        scroller && scroller[0] && (scroller[0].scrollTop = 0);
    }
    
    throttleFunction = (method) => {
        return () => {
            let hasLoading = this.props.hasOwnProperty("loading");
            let shortTime = this.props.intervalTime;
            let longTime = this.props.overtime;
            let curTime = new Date().getTime();
            let canScroll = false;
            let interval = curTime - this.startTime;
            if (hasLoading) {
                canScroll = this.props.loading ? interval >= longTime : interval >= shortTime;
            } else {
                canScroll = interval >= shortTime;
            }
            if (canScroll) {
                this.startTime = curTime;
                method();
            }
        }
    }
    
    onScroll = (event) => {
        const dom = event.currentTarget;
        const {scrollTop, clientHeight, scrollHeight} = dom;
        if (scrollTop + clientHeight >= scrollHeight - this.props.offset) {
            this.throttleFunction(this.props.onScrollEnd)()
        }
    }
    
    render() {
        return (
            <WeaNewScroll onScroll={this.onScroll} height={this.props.height}>
                {this.props.children}
            </WeaNewScroll>
        );
    }
}

WeaNewScrollPagination.defaultProps = {
    offset: 30,
    overtime: 5000,
    intervalTime: 500
};

WeaNewScrollPagination.propTypes = {
    onScrollEnd: T.func.isRequired,//滚动到最末尾时执行的函数
    height: T.number,//高度，可不传
    loading: T.bool,//加载状态。传入此值时，会以该值为依据判断是否可加载。传入该值时，若为true,则加载间隔为overtime，否则，加载间隔为intervalTime，不传时，加载间隔为intervalTime。
    offset: T.number,//与底部的偏差，距底部多少距离时执行方法,默认30px
    overtime: T.number,//超时时间，默认5000毫秒
    intervalTime: T.number//间隔时间, 默认500毫秒
}

export default WeaNewScrollPagination;
